package service

import (
	"MyBlogv2/common/HttpCode"
	"MyBlogv2/common/helper"
	"MyBlogv2/common/models"
	"MyBlogv2/common/response"
	"context"
	"fmt"
	"github.com/gin-gonic/gin"
	"time"
)

func SendCodeOfRegister(c *gin.Context) {
	email := c.Query("email")
	fmt.Println(email)
	typeOfCode := c.Query("type")

	if typeOfCode != "register" && typeOfCode != "reset" && typeOfCode != "resetEmail" {
		response.ResponseError(c, HttpCode.PARAM_ERROR)
		return
	}
	
	// 如果是注册类型，检查邮箱是否已存在
	if typeOfCode == "register" {
		var count int64
		models.Db.Model(new(models.User)).Where("email = ?", email).Count(&count)
		if count > 0 {
			response.ResponseError(c, HttpCode.USERNAME_OR_EMAIL_EXIST)
			return
		}
	}
	
	code := helper.GetRandNumber()
	err := helper.SendCode(email, code)
	if err != nil {
		response.ResponseError(c, HttpCode.FAILURE)
		return
	}
	models.RDb.Set(context.Background(), email, code, time.Minute*15)
	response.ResponseOK(c, nil)
}
